package com.erp.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    public synchronized static List<File> getRecursionFiles(File dir) {
        List<File> files = new ArrayList<>();
        if (dir.isDirectory()) {
            for (File file : dir.listFiles()) {
                files.addAll(getRecursionFiles(file));
            }
        } else {
            files.add(dir);
        }
        return files;
    }

    public synchronized static void read(String path, String encoding, List<String> content) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), encoding));
        for (String s : content) {
            bufferedWriter.write(s);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }

    public synchronized static List<String> read(String path, String encoding) throws IOException {
        List<String> content = new ArrayList<String>();
        try {
            File file = new File(path);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            String line = null;
            while ((line = reader.readLine()) != null) {
                content.add(line);
            }
            reader.close();
        } catch (Exception e) {
        }
        return content;
    }

    public synchronized static boolean copySingleFile(String oldPath, String newPath) {
        boolean flag = false;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                fs.close();
                inStream.close();
                flag = true;
            }
        } catch (Exception e) {
        }
        return flag;
    }
}
